import os
import re

def count_chinese_chars(text):
    # 统计中文字符数
    pattern = re.compile(r'[\u4e00-\u9fa5]')
    return len(pattern.findall(text))

def count_words_in_file(file_path):
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            content = f.read()
            return count_chinese_chars(content)
    except Exception as e:
        print(f"Error reading {file_path}: {e}")
        return 0

def format_number(num):
    return f"{num:,}"

def main():
    base_dir = os.path.dirname(os.path.abspath(__file__))
    total_words = 0
    directory_stats = {}

    # 遍历所有目录
    for root, dirs, files in os.walk(base_dir):
        # 跳过统计脚本本身
        if 'count_words.py' in files:
            files.remove('count_words.py')

        # 只统计.md文件
        md_files = [f for f in files if f.endswith('.md')]
        if not md_files:
            continue

        # 获取相对路径作为目录名
        rel_path = os.path.relpath(root, base_dir)
        if rel_path == '.':
            dir_name = '根目录'
        else:
            dir_name = rel_path

        dir_total = 0
        file_stats = []

        # 统计每个文件的字数
        for file in md_files:
            file_path = os.path.join(root, file)
            word_count = count_words_in_file(file_path)
            dir_total += word_count
            file_stats.append((file, word_count))

        if dir_total > 0:
            directory_stats[dir_name] = {
                'total': dir_total,
                'files': file_stats
            }
            total_words += dir_total

    # 打印统计结果
    print('\n=== 小说项目字数统计 ===\n')
    
    # 按目录字数从大到小排序
    sorted_dirs = sorted(directory_stats.items(), 
                        key=lambda x: x[1]['total'], 
                        reverse=True)

    for dir_name, stats in sorted_dirs:
        print(f'\n【{dir_name}】 - 总字数：{format_number(stats["total"])}字')
        # 按文件字数从大到小排序
        sorted_files = sorted(stats['files'], 
                             key=lambda x: x[1], 
                             reverse=True)
        for file_name, count in sorted_files:
            print(f'  {file_name}: {format_number(count)}字')

    print(f'\n总计：{format_number(total_words)}字')

if __name__ == '__main__':
    main()